import psutil
import time
import gradio as gr
import matplotlib.pyplot as plt
from io import BytesIO

# 存储 CPU 使用情况的列表
cpu_usage_history = []

def get_cpu_usage():
    # 记录当前 CPU 使用率并返回
    cpu_usage = psutil.cpu_percent(interval=1)
    cpu_usage_history.append(cpu_usage)
    return cpu_usage

def plot_cpu_usage():
    # 绘制 CPU 使用情况的折线图
    plt.figure(figsize=(10, 5))
    plt.plot(cpu_usage_history, label='CPU Usage (%)')
    plt.xlabel('Time')
    plt.ylabel('CPU Usage (%)')
    plt.title('CPU Usage Over Time')
    plt.legend()
    
    # 将图表保存到内存中的 BytesIO 对象
    buf = BytesIO()
    plt.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    
    return buf

# 创建 Gradio 应用
with gr.Blocks() as demo:
    with gr.Row():
        gr.Markdown("## CPU Usage Over Time")
        graph_output = gr.Image(label="CPU Usage Graph", show_label=False)
    
    # 更新图表的按钮
    update_graph = gr.Button("Update Graph")
    update_graph.click(plot_cpu_usage, outputs=graph_output)

    # 定时获取 CPU 使用率的按钮
    check_cpu = gr.Button("Check CPU Usage")
    check_cpu.click(get_cpu_usage)

demo.launch()

"""有报错, 还没处理"""